package com.czk.security.service.impl;

import com.czk.security.model.AuthenticationRequest;
import com.czk.security.model.UserDto;
import com.czk.security.service.AuthenticationService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/3/18 22:49
 */
@Service
public class AuthenticationServiceImpl implements AuthenticationService {
    private static Map<String, UserDto> userMap;

    /**
     * 模拟数据
     */
    static {
        Set<String> set1 = new HashSet<>();
        // p1和p2是权限标识符，需要和路由相对应
        set1.add("p1");
        Set<String> set2 = new HashSet<>();
        set2.add("p2");
        userMap = new HashMap<>(16);
        userMap.put("zhangsan", new UserDto("1010", "zhangsan", "123", "张三", "133443", set1));
        userMap.put("lisi", new UserDto("1011", "lisi", "456", "李四", "144553", set2));
    }

    @Override
    public UserDto authentication(AuthenticationRequest authenticationRequest) {
        // 校验参数是否为空
        if (authenticationRequest == null || StringUtils.isEmpty(authenticationRequest.getUsername()) || StringUtils.isEmpty(authenticationRequest.getPassword())) {
            throw new RuntimeException("账号或密码为空");
        }
        // 查询数据
        UserDto userDto = getUserDto(authenticationRequest.getUsername());
        if (userDto == null) {
            throw new RuntimeException("用户名不存在");
        }
        // 拿到密码
        if (!userDto.getPassword().equals(authenticationRequest.getPassword())) {
            throw new RuntimeException("用户密码错误");
        }
        return userDto;
    }

    private UserDto getUserDto(String username) {
        return userMap.get(username);

    }
}
